﻿using System;
using System.IO;
using System.Text;

namespace Infrastructure.Common.Log.Imp
{
    /// <summary>
    ///     亦宣和小皇
    /// </summary>
    public class Log : ILog
    {
        private readonly string _logPath;

        public Log(string logPath)
        {
            _logPath = logPath;
        }

        public void WriteInformation(string message)
        {
            WriteMessage(message, LogLevel.Information);
        }

        public void WriteWarning(string message)
        {
            WriteMessage(message, LogLevel.Warning);
        }

        public void WriteError(string message)
        {
            WriteMessage(message, LogLevel.Error);
        }

        /// <summary>
        ///     格式
        ///     {日志等级}{时间}:{内容}
        ///     demo:信息: 用户登录 2014-3-30 21：00：00
        ///     错误: 用户登录失败 2014-3-30 21：00：00
        ///     警告: 用户重复登录 2014-3-30 21：00：00
        ///     时间用当前时间
        /// </summary>
        /// <param name="message"></param>
        /// <param name="level"></param>
        private void WriteMessage(string message, LogLevel level)
        {
            string compmess = string.Format("{0}: {1} {2}", GetLogLevel(level), message,
                DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            var fi = new FileInfo(_logPath);
            //如果不存在就创建
            using (StreamWriter sw = !fi.Exists ? fi.CreateText() : new StreamWriter(_logPath, true, Encoding.UTF8))
            {
                sw.WriteLine(compmess);
                sw.Close();
            }
        }

        private string GetLogLevel(LogLevel level)
        {
            string leve = "";
            switch (level)
            {
                case LogLevel.Error:
                {
                    leve = "错误";
                    break;
                }
                case LogLevel.Information:
                {
                    leve = "信息";
                    break;
                }
                case LogLevel.Warning:
                {
                    leve = "警告";
                    break;
                }
            }
            return leve;
        }
    }
}